package cn.congine.wizarpos.mall.dao.hibernate;

import java.util.List;

import org.hibernate.FlushMode;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import cn.congine.wizarpos.mall.dao.WxAddressDao;
import cn.congine.wizarpos.mall.model.WxAddress;
import cn.congine.wizarpos.mall.utils.Function;

@Repository("wxAddressDao")
public class WxAddressDaoHibernate extends GenericDaoHibernate<WxAddress>
		implements WxAddressDao {

	public WxAddressDaoHibernate() {
		super(WxAddress.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<WxAddress> getWxAddressListByCardId(String cardId) {
		Query query = getSession().createQuery(
				"from WxAddress where cardId = :cardId").setParameter("cardId",
				cardId);
		return (List<WxAddress>) query.list();
	}

	@Override
	public WxAddress getDefaultWxAddress(String cardId) {
		Query query = getSession().createQuery(
				"from WxAddress where cardId = :cardId and defaultState='1'")
				.setParameter("cardId", cardId);
		return (WxAddress) query.uniqueResult();
	}

	@Override
	public WxAddress getWxAddressId(String id) {
		Query query = getSession()
				.createQuery("from WxAddress where id = :id ").setParameter(
						"id", id);
		return (WxAddress) query.uniqueResult();
	}

	@Override
	public WxAddress save(WxAddress obj) {
		String uuid = Function.getUid();
		obj.setId(uuid);
		String sql = "INSERT INTO wx_address (id, card_id, address, username, phone, default_state, zip_code, mid)"
				+ "values(?,?,?,?,?,?,?,?)";

		this.getSession().setFlushMode(FlushMode.MANUAL);
		Query q = getSession().createSQLQuery(sql);
		q.setString(0, uuid);
		q.setString(1, obj.getCardId());
		q.setString(2, obj.getAddress());
		q.setString(3, obj.getUsername());
		q.setString(4, obj.getPhone());
		q.setString(5, obj.getDefaultState());
		q.setString(6, obj.getZipCode());
		q.setString(7, obj.getMid());
		q.executeUpdate();
		return obj;
	}

	@Override
	public void update(WxAddress obj) {
		String sql = "UPDATE wx_address SET address = ?, username = ?, phone = ?,"
				+ " default_state = ?, zip_code = ?, card_id = ? WHERE id = ? and mid = ?";

		this.getSession().setFlushMode(FlushMode.MANUAL);
		Query q = getSession().createSQLQuery(sql);

		q.setString(0, obj.getAddress());
		q.setString(1, obj.getUsername());
		q.setString(2, obj.getPhone());
		q.setString(3, obj.getDefaultState());
		q.setString(4, obj.getZipCode());
		q.setString(5, obj.getCardId());
		q.setString(6, obj.getId());
		q.setString(7, obj.getMid());
		
		q.executeUpdate();
	}
	
	@Override
	public void remove(String id, String mid) {
		String hql = "delete From WxAddress where id = ? and mid=?";
		this.getSession().setFlushMode(FlushMode.MANUAL);
		Query q = getSession().createQuery(hql);
		q.setString(0, id);
		q.setString(1, mid);
		q.executeUpdate();
	}
}
